package utils;

import java.util.Random;

/**
 * 数据加密/解密类<br>
 * B为二进制，D为十进制，H为十六进制
 * 
 * @author jungle
 *
 */
public class FCDataDecryptOrEncryption {

	private Random random = new Random();

	protected FCDataDecryptOrEncryption() {
	}

	/**
	 * 数据加密
	 * 
	 * @param data
	 * @return
	 */
	public String dataEncryption(String data) {
		String n = "", m = "";
		for (int i = 0; i < data.length();) {
			if (data.charAt(i) < 128) {
				n = BtoVL(DtoB(data.charAt(i)));
				if (i + 1 < data.length()) {
					if (data.charAt(++i) < 128) {
						n += BtoVL(DtoB(data.charAt(i++)));
					} else {
						n += "00000000";
					}
				} else {
					n += "00000000";
					i++;
				}
				m += (char) BtoD(n);
			} else {
				m += (char) (random.nextInt(90) + 33);
				n = buqi(16, DtoB(data.charAt(i++)));
				m += (char) BtoD(BtoVL(n.substring(0, 8)) + BtoVL(n.substring(8)));
			}
		}
		return m;
	}

	/**
	 * 数据解密
	 * 
	 * @param data
	 * @return
	 */
	public String dataDecrypt(String data) {
		String n = "";
		if (data != null) {
			for (int i = 0; i < data.length(); i++) {
				if (data.charAt(i) < 128) {
					String k = buqi(16, DtoB(data.charAt(i)));
					n += (char) BtoD(BtoVR(k.substring(0, 8)) + BtoVR(k.substring(8)));
				} else {
					String k = buqi(16, DtoB(data.charAt(i)));
					n += (char) BtoD(BtoVR(k.substring(0, 8)));
					if (!k.substring(8).equals("00000000")) {
						n += (char) BtoD(BtoVR(k.substring(8)));
					}
				}
			}
		} else
			return null;
		return n;
	}

	/**
	 * 十进制转二进制
	 * 
	 * @param num
	 * @return
	 */
	public String DtoB(int num) {
		String n = "";
		while (true) {
			n = num % 2 + n;
			num = num / 2;
			if (num == 0) {
				return n;
			}
		}
	}

	/**
	 * 二进制转十进制
	 * 
	 * @param num
	 * @return
	 */
	public int BtoD(String num) {
		int n = 0, j = num.length() - 1;
		for (int i = 0; i < num.length(); i++) {
			n += (num.charAt(i) - '0') * (int) Math.pow(2, j--);
		}
		return n;
	}

	/**
	 * 二进制加密
	 * 
	 * @param num
	 * @return
	 */
	public String BtoVL(String num) {
		num = buqi(8, num);
		return num.substring(5) + num.substring(0, 5);
	}

	/**
	 * 二进制解密
	 * 
	 * @param num
	 * @return
	 */
	public String BtoVR(String num) {
		num = buqi(8, num);
		return num.substring(3) + num.substring(0, 3);
	}

	/**
	 * 高位补0
	 * 
	 * @param num
	 * @param str
	 * @return
	 */
	public String buqi(int num, String str) {
		while (true) {
			if (str.length() < num) {
				str = '0' + str;
			} else {
				break;
			}
		}
		return str;
	}
}
